package com.gucheng.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.gucheng.springframework.beans.BeansException;
import com.gucheng.springframework.beans.PropertyValue;
import com.gucheng.springframework.beans.PropertyValues;
import com.gucheng.springframework.beans.factory.config.BeanDefinition;
import com.gucheng.springframework.beans.factory.config.BeanReference;


import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    //使用CGLIB库创建bean实例
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();


    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, beanName, args);
            //给 Bean 填充属性
            applyPropertyValues(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }


    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        //1.通过Bean定义(beanDefinition)获取Bean的类信息
        Class<?> beanClass = beanDefinition.getBeanClass();
        //2.获取这个类的所有构造函数
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        //3.遍历bean定义中的所有构造函数，找到一个匹配的构造函数
        for (Constructor ctor : declaredConstructors) {
            //构造函数的参数类型数量要与传入的参数（args）数量相同
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        //创建bean实例
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    /**
     * Bean 属性填充
     */
    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            //从BeanDefinition中获取属性值集合PropertyValues
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            //遍历PropertyValues集合中的每一个属性值PropertyValue
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                //对于每个属性值，获取其名称name和值value
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                //通过value判断是否依赖了其他的Bean
                if (value instanceof BeanReference) {
                    // A依赖 B，获取 B 的实例化
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                //属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        }catch (Exception e){
            throw new BeansException("Error setting property values on bean: " + beanName);
        }

    }


    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

}
